/*
 * @Author: 凌宇king
 * @Date: 2022-09-11 13:55:40
 * @LastEditTime: 2022-09-15 12:54:25
 */
//加载express

const express = require('express');
//实例路由
const router = express.Router();
//导入数据模型 
const address = require('../model/address')
//===============API写下面================================================
//小程序端 添加地址信息
router.post('/wxAddressAdd', async (req, res) => {
    try {
        //设置默认地址 
        const { openid, isDefault } = req.body;
        if (isDefault) {
            //将我的默认地址isDefault设置为false 
            await address.findOneAndUpdate({ openid, isDefault }, { isDefault: false });
        }
        await address.create(req.body);
        res.send('success');
    } catch (err) {
        res.send('fail')
        console.log('add:' + err);
    }
})
//小程序端 获取地址列表
router.get('/wxAddress',
    async (req, res) => {
        try {
            const addressList = await address.find({ openid: req.query.openid }).sort({ addTime: -1 });
            res.send({ message: 'success', result: addressList });
        }
        catch (err) {
            res.send({ message: 'fail', result: err })
        }
    })
//小程序端 保存地址信息
router.post('/wxAddressSave', async (req, res) => {
    try {
        //设置默认地址
        const { openid, isDefault, _id } = req.body;
        // console.log(_id)
        if (isDefault) {
            //遍历数据库，将我的地址中isDefault设置为false
            await address.findOneAndUpdate({ openid, isDefault }, { isDefault: false });
        }
        if (_id) {
            //id存在，则修改地址信息 
            await address.findByIdAndUpdate(_id, req.body)

        } else {
            //id不存在，执行添加操作 
            await address.create(req.body);
        }
        res.send('success');

    }
    catch (err) {
        res.send('fail')
        console.log('add:' + err);
    }
})
/* 删除地址信息 */
router.get('/wxDelAddress', async (req, res) => {
    try {
        await address.deleteOne({ _id: req.query._id })
        res.send('success');
    } catch (error) {
        console.log(error)
    }
})
//===============API写在上面=============================================
//导出路由
module.exports = router;